<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateUserCommentAPIRequest;
use App\Http\Requests\API\UpdateUserCommentAPIRequest;
use App\Models\UserComment;
use App\Repositories\UserCommentRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class UserCommentController
 * @package App\Http\Controllers\API
 */

class UserCommentAPIController extends AppBaseController
{
    /** @var  UserCommentRepository */
    private $userCommentRepository;

    /**
     * Display a listing of the UserComment.
     * GET|HEAD /userComments
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->userCommentRepository->pushCriteria(new RequestCriteria($request));
        $this->userCommentRepository->pushCriteria(new LimitOffsetCriteria($request));
        $userComments = $this->userCommentRepository->all();

        return $this->sendResponse($userComments->toArray(), 'User Comments retrieved successfully');
    }

    /**
     * 小程序查看需要加条件 is_hot = 1
     * @param TicketModelRepository $repo
     */
    public function search(UserCommentRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $searchOptions['status'] = 0;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * 小程序查看需要加条件 is_hot = 1
     * @param TicketModelRepository $repo
     */
    public function apiSearch(UserCommentRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $searchOptions['status'] = 0;
        $searchOptions['is_hot'] = 1;

        $ret = $repo->search($searchOptions, $sortOptions);

        $comment = UserComment::where('user_id', $this->request->attributes->get('user_id'))->get()->first();
        if (!empty($comment)) {
            $lists = $ret['lists'];
            if (count($lists) == 0) {
                return $this->success(['lists' => []]);
            }

            array_unshift($lists, $comment->toArray());
            array_pop($lists);
            $ret['lists'] = $lists;

            return $this->success($ret);
        } else {
            $lists = $ret['lists'];
            if (count($lists) == 0) {
                return $this->success(['lists' => []]);
            }
            $ret['lists'] = $lists;

            return $this->success($ret);
        }

    }

    /**
     * Store a newly created UserComment in storage.
     * POST /userComments
     *
     * @param CreateUserCommentAPIRequest $request
     *
     * @return Response
     */
    public function store(UserCommentRepository $userCommentRepository)
    {
        $user = $this->request->attributes->get('user');
        $userId = $this->request->attributes->get('user_id');

        $comment = UserComment::where('user_id', $userId)->where('status', 0)->get()->first();
        if (!empty($comment)) {
            return $this->error(1, '已评论');
        }

        $input = $this->request->all();

        $input['user_id'] = $userId;
        $input['avatar'] = $user->avatar;
        $input['nickname'] = $user->nickname;

        $userComments = $userCommentRepository->create($input);

        return $this->sendResponse($userComments->toArray(), '评论成功');
    }

    /**
     * Display the specified UserComment.
     * GET|HEAD /userComments/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, UserCommentRepository $userCommentRepository)
    {
        /** @var UserComment $userComment */
        $userComment = $userCommentRepository->findWithoutFail($id);

        if (empty($userComment)) {
            return $this->sendError('User Comment not found');
        }

        return $this->sendResponse($userComment->toArray(), 'User Comment retrieved successfully');
    }

    /**
     * 无需更新
     * Update the specified UserComment in storage.
     * PUT/PATCH /userComments/{id}
     *
     * @param  int $id
     * @param UpdateUserCommentAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UserCommentRepository $userCommentRepository)
    {
        $input = $this->request->all();

        /** @var UserComment $userComment */
        $userComment = $userCommentRepository->findWithoutFail($id);

        if (empty($userComment)) {
            return $this->sendError('User Comment not found');
        }

        $userComment = $userCommentRepository->update($input, $id);

        return $this->sendResponse($userComment->toArray(), 'UserComment updated successfully');
    }

    /**
     * Remove the specified UserComment from storage.
     * DELETE /userComments/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var UserComment $userComment */
        $userComment = $this->userCommentRepository->findWithoutFail($id);

        if (empty($userComment)) {
            return $this->sendError('User Comment not found');
        }

        $userComment->delete();

        return $this->sendResponse($id, 'User Comment deleted successfully');
    }

    /**
     * 批量删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchDestroy()
    {
        $ids = $this->request->get('ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $ids = explode(',', $ids);
        // 删除ticket
        UserComment::whereIn('id', $ids)->update(['status' => 2]);

        return $this->success([], '操作成功');
    }

    /**
     * batch 精选
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchSet()
    {
        $ids = $this->request->get('ids');
        if (empty($ids)) {
            return $this->sendError('id不为空');
        }

        $isHot = (int) $this->request->get('is_hot');

        if ($isHot !=0 && $isHot != 1) {
            return $this->sendError('is_hot 参数错误');
        }

        $ids = explode(',', $ids);
        // 设置为精选,或者取消精选
        UserComment::whereIn('id', $ids)->update(['is_hot' => $isHot]);

        return $this->success([], '操作成功');
    }

    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'store' => [
            'comment' => 'required|string',
        ],
    ];
}
